#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai

import sys
import re
import argparse
from datetime import datetime, timedelta

def get_opt_count_from_this(cyg_count, nm_list):
    index = cyg_count
    while index < len(nm_list):
        if nm_list[index][1] == 1:
            index += 1
        else:
            break
    return index - cyg_count

def loop_once(cyg_file, nm_list):
    global args
    cyg_list = []
    cyg_count = 0
    match_count = 0

    #check option count
    cyg_opt_count = get_opt_count_from_this(cyg_count, nm_list)
    #print "cyg_opt_count %d" % cyg_opt_count

    for cyg_line in cyg_file:
        if cyg_count == len(nm_list):
            break

        cyg_opt = 0
        while cyg_opt < cyg_opt_count + 1:
            cyg_rx = "^\[(.+)\] *(%s.*)" % nm_list[cyg_count + cyg_opt][0]
            cyg_re = re.match(cyg_rx, cyg_line.rstrip('\n\r'))
            if cyg_re != None:
                if args.terminal == "tera":
                    #### for tera term ####
                    cyg_dt = datetime.strptime(cyg_re.group(1), "%a %b %d %H:%M:%S.%f %Y")
                    #cyg_dt = datetime.strptime(cyg_re.group(1), "%m-%d:%H:%M:%S:%f")
                else:
                    #### for minicom ####
                    cyg_dt = datetime.strptime(cyg_re.group(1), "%Y-%m-%d %H:%M:%S.%f")
                #print cyg_line.rstrip('\n\r')
                #print cyg_dt
                cyg_entry = [cyg_re.group(2).rstrip('\n\r'), cyg_dt]
                cyg_list.append(cyg_entry)
                cyg_count += 1
                cyg_count += cyg_opt
                match_count += 1
                cyg_opt_count = get_opt_count_from_this(cyg_count, nm_list)
                #print "cyg_opt_count %d" % cyg_opt_count
                break
            else:
                cyg_opt += 1

    if cyg_count != len(nm_list):
        print "Parse Error!!! the log could not go through all check points %d/%d match %d" % (cyg_count, len(nm_list) , match_count)

    cyg_base = None
    cyg_last = None
    for item in cyg_list:
        if cyg_base == None:
            cyg_base = item[1]
        if cyg_last != None:
            cyg_delta = item[1] - cyg_last
            print "\tDelta %s" % (cyg_delta)
        cyg_last = item[1]
        print "[%s] %s" % (item[1] - cyg_base, item[0])

    return match_count, cyg_count


def main():
    global args

    #### args parse
    parser = argparse.ArgumentParser(description="Parse the logs with check points.")
    parser.add_argument("-t", "--terminal", help="assign nm path.", default="tera")
    parser.add_argument("checkpoint", help="assign check point file")
    parser.add_argument("log", help="assign console log file")
    args = parser.parse_args()
    #if len(sys.argv) < 3:
    #    print "Usage: %s" % sys.argv[0]
    #    sys.exit(2)

    nm_list = []
    nm_file = open(args.checkpoint, 'r')
    for nm_line in nm_file:
        nm_re = re.match("^#.*", nm_line)
        if nm_re:
            continue
        option = 0
        nm_re = re.match("^!.*", nm_line)
        if nm_re:
            option = 1
        #print "option %d" % option
        nm_entry = [nm_line.lstrip('!').rstrip('\n\r'), option]
        nm_list.append(nm_entry)

    print "Number of Check Points %d" % len(nm_list)
    #print nm_list

    cyg_file = open(args.log, 'r')
    loops = 0

    match, count = loop_once(cyg_file, nm_list)
    while count != 0:
        print "Loop count %d matched %d checked %d/%d\n" % (loops, match, count, len(nm_list))
        match, count = loop_once(cyg_file, nm_list)
        loops += 1


if __name__ == "__main__":
    main()
